extends Node2D
class_name Fireball

@export var speed: float = 3000.0
@export var damage: float = 50.0
@export var lifetime: float = 3.0
@export var explosion_radius: float = 100.0


var velocity: Vector2 = Vector2.ZERO
var is_exploding: bool = false
var explosion_particles: Array[Node2D] = []
## 是否是敌人的火球
var is_enemy = false

@onready var trail_particles: GPUParticles2D = %TrailParticles
@onready var fireball_sprite: AnimatedSprite2D = %FireballSprite
@onready var fireball_area: Area2D = $FireballArea
@onready var collision_shape: CollisionShape2D = $FireballArea/CollisionShape2D

func _ready() -> void:
	# 设置爆炸区域的碰撞形状
	var circle_shape = CircleShape2D.new()
	circle_shape.radius = explosion_radius
	
	# 连接爆炸区域的信号
	fireball_area.body_entered.connect(_on_explosion_body_entered)
	fireball_area.area_entered.connect(_on_explosion_area_entered)
	
	# 设置生命周期
	var timer = get_tree().create_timer(lifetime)
	timer.timeout.connect(_on_lifetime_timeout)
	
	if is_enemy:
		fireball_area.collision_mask = 8
	else:
		fireball_area.collision_mask = 16
	
	
func _physics_process(delta: float) -> void:
	if is_exploding:
		return
	# 移动火球
	global_position += velocity * delta

func init(start_position: Vector2, direction: Vector2, _is_enemy = false) -> void:
	global_position = start_position
	velocity = direction.normalized() * speed
	is_enemy = _is_enemy
	self.look_at(global_position + direction * 100)
func explode() -> void:
	if is_exploding:
		return
	
	is_exploding = true
	print("火球爆炸！")
	
	# 隐藏火球精灵
	fireball_sprite.visible = false
	
	# 启用爆炸区域
	fireball_area.monitoring = true
	
	# 创建爆炸粒子效果
	_create_explosion_particles()
	trail_particles.queue_free()
	# 延迟销毁节点
	await get_tree().create_timer(1.0).timeout
	queue_free()

func _create_explosion_particles() -> void:
	# 创建多个爆炸粒子
	for i in range(30):
		var particle = _create_particle()
		explosion_particles.append(particle)
		add_child(particle)
		
		# 随机方向
		var angle = randf() * TAU
		var distance = randf_range(30.0, explosion_radius)
		var target_pos = global_position + Vector2(cos(angle), sin(angle)) * distance
		
		# 创建移动动画
		var tween = create_tween()
		tween.tween_property(particle, "global_position", target_pos, 0.8)
		tween.parallel().tween_property(particle, "modulate:a", 0.0, 0.8)
		tween.parallel().tween_property(particle, "scale", Vector2(0.1, 0.1), 0.8)
		tween.tween_callback(particle.queue_free)

func _create_particle() -> Node2D:
	var particle = Node2D.new()
	
	# 创建像素风格的粒子精灵
	var sprite = Sprite2D.new()
	sprite.texture = _create_pixel_texture()
	sprite.modulate = Color(randf_range(0.8, 1.0), randf_range(0.3, 0.7), 0.0, 1.0)
	particle.add_child(sprite)
	
	# 随机大小
	var scale_factor = randf_range(0.5, 1.5)
	particle.scale = Vector2(scale_factor, scale_factor)
	
	return particle

func _create_pixel_texture() -> Texture2D:
	# 创建像素风格的粒子纹理
	var image = Image.create(6, 6, false, Image.FORMAT_RGBA8)
	image.fill(Color(0, 0, 0, 0))  # 透明背景
	
	# 创建火焰粒子效果
	var colors = [
		Color(1, 0.8, 0, 1),    # 黄色
		Color(1, 0.5, 0, 1),    # 橙色
		Color(1, 0.3, 0, 1),    # 红色
		Color(1, 0.9, 0.3, 1)   # 亮黄色
	]
	
	# 随机填充像素
	for x in range(6):
		for y in range(6):
			if randf() > 0.4:  # 60%概率设置像素
				var color = colors[randi() % colors.size()]
				image.set_pixel(x, y, color)
	
	var texture = ImageTexture.create_from_image(image)
	return texture

func _on_explosion_body_entered(body: Node2D) -> void:
	if body.has_method("enemy_hurt"):
		body.enemy_hurt(self, damage, "fireball", Color.ORANGE)
		print("爆炸伤害: ", damage)

func _on_explosion_area_entered(area: Area2D) -> void:
	if area.has_method("enemy_hurt") and !is_enemy:
		var is_critical = false
		var crit_chance = Utils.get_player_stats_value("critical_chance")
		var crit_multiplier = Utils.get_player_stats_value("critical_multiplier")
		var is_skill_critical = Utils.get_player_stats_value("is_skill_critical")
		if is_skill_critical and crit_chance > 0 and randf() * 100 < crit_chance:
			is_critical = true
			damage *= crit_multiplier
		# 兼容旧版本，直接调用enemy_hurt
		area.enemy_hurt(self, damage, is_critical, Color.ORANGE)
		
	if area.has_method("hurt") and is_enemy:
		area.hurt(self, damage)
		
func _on_lifetime_timeout() -> void:
	explode()

func _on_area_entered(_area: Area2D) -> void:
	explode()

func _on_body_entered(_body: Node2D) -> void:
	explode()
